package id.co.shuba.spamobile.activities;

import java.util.ArrayList;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.viewpagerindicator.TitlePageIndicator;

import id.co.shuba.spamobile.App;
import id.co.shuba.spamobile.CustomSessionApplication;
import id.co.shuba.spamobile.LogoutReceiver;
import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.Sessions;
import id.co.shuba.spamobile.data.DSARDB;
import id.co.shuba.spamobile.data.DatabaseHandler;
import id.co.shuba.spamobile.data.ISharedDB;
import id.co.shuba.spamobile.data.ProspectDB;
import id.co.shuba.spamobile.data.TransactionLogDB;
import id.co.shuba.spamobile.list.DSARListFragment;
import id.co.shuba.spamobile.list.DSARListFragment.OnDSARSelectedListener;
import id.co.shuba.spamobile.model.UserInfo;
import id.co.shuba.spamobile.util.StyleUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;

public class PipelineViewActivity extends SherlockFragmentActivity
	implements ViewPager.OnPageChangeListener, ISharedDB {	
	
	private static final boolean DETAIL_REQUIRED_FOR_DSAR = true;
	private String _prospectID;	
	
	private DatabaseHandler _db;	
	private ProspectDB _prospectDB;
		
	private DSARDB _dsarDB;
	private PipelineViewFragment _pipelineFragment;
	private DSARListFragment _dsarFragment;
	private ViewPager _pager;
	
	private MenuItem _menuAdd;
	private MenuItem _menuEdit;
	private MenuItem _menuDelete;
	private MenuItem _menuDSAR;
	private MenuItem _menuProspect;
	private boolean _isComplete;
	
	private LogoutReceiver logoutReceiver;

	private void setUpLogoutReceiver() {
		IntentFilter intentFilter = new IntentFilter();
	    intentFilter.addAction("id.co.shuba.spamobile.ACTION_LOGOUT");
	    logoutReceiver = new LogoutReceiver(this);
	    registerReceiver(logoutReceiver, intentFilter);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {		
		super.onSaveInstanceState(outState);
		outState.putString("_pipelineFragment", _pipelineFragment.getTag());
		outState.putString("_dsarFragment", _dsarFragment.getTag());
	}
		
	
	@Override
	public void onUserInteraction() {		
		super.onUserInteraction();
		((CustomSessionApplication) getApplication()).touch();
		if (App.DEBUG) {			
			Log.d("User Interaction", "User interaction to "+this.toString());			
		}
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_pipeline_view);
		setUpLogoutReceiver();
		
		Bundle bundle = getIntent().getExtras();		
		_prospectID = bundle.getString("prospectID");		

		StyleUtil.applyStyle(this);
		
		_db = new DatabaseHandler(this);		
		_prospectDB = new ProspectDB(_db);		
		_dsarDB = new DSARDB(_db);		
						
		_pager = (ViewPager)findViewById(R.id.pager);         					    					
		
		ArrayList<String> titles = new ArrayList<String>();
		titles.add("PIPELINE");
		titles.add("DSAR");
				
		FragmentManager fm = getSupportFragmentManager();
		if (savedInstanceState != null) {
			_pipelineFragment = (PipelineViewFragment) fm.findFragmentByTag(savedInstanceState.getString("_pipelineFragment"));
			_dsarFragment = (DSARListFragment) fm.findFragmentByTag(savedInstanceState.getString("_dsarFragment"));
	    } else {	  			
	    	_pipelineFragment = (PipelineViewFragment) Fragment.instantiate(this, PipelineViewFragment.class.getName());
			_dsarFragment = (DSARListFragment) Fragment.instantiate(this, DSARListFragment.class.getName());
	    }				
		
		ArrayList<Fragment> fragments = new ArrayList<Fragment>();
		fragments.add(_pipelineFragment);
		fragments.add(_dsarFragment);
		
		SimplePagerAdapter adapter = new SimplePagerAdapter(
				getSupportFragmentManager(), titles, fragments);	
		
		_pager.setAdapter(adapter);		
		
		_dsarFragment.setOnDSARSelectedListener(new OnDSARSelectedListener() {			
			@Override
			public void onDSARSelected(int id, boolean lastItem) {
				editDSAR(id, lastItem);
			}
		});
		
		TitlePageIndicator indicator = (TitlePageIndicator)findViewById(R.id.indicator);
        indicator.setViewPager(_pager);        
        indicator.setOnPageChangeListener(this);
		
		_pipelineFragment.setProspectID(_prospectID);
		_dsarFragment.setProspectID(_prospectID);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.activity_pipeline_view, menu);

		//_isComplete = _prospectDB.isProspect(_prospectID);
		
		_menuDSAR = menu.findItem(R.id.menu_dsar);
		_menuDSAR.setEnabled(_isComplete);			
				
		_menuAdd = menu.findItem(R.id.menu_add);
		_menuEdit = menu.findItem(R.id.menu_edit);
		_menuDelete = menu.findItem(R.id.menu_delete);	
		_menuProspect = menu.findItem(R.id.menu_data_pelengkap);
		
		//_menuAdd.setVisible(false);
		
		setActionBar(_pager.getCurrentItem());
		
		return true;
	}

	private void edit() {
		Intent intent = new Intent(this, FormPipelineActivity.class);
		intent.putExtra("prospectID", _prospectID);

		startActivityForResult(intent, App.REQUEST_EDIT_PIPELINE);
	}

	private void prospect() {
		Intent intent = new Intent(this, FormProspectActivity.class);
		intent.putExtra("prospectID", _prospectID);

		startActivityForResult(intent, App.REQUEST_EDIT_PROSPECT);
	}
	
	private void addDSAR() {
		Intent intent = new Intent(PipelineViewActivity.this,
				FormDSARActivity.class);
		intent.putExtra("prospectID", _prospectID);
		startActivityForResult(intent, App.REQUEST_EDIT_DSAR);
	}

	private void editDSAR(int id, boolean lastItem) {
		Intent intent = new Intent(PipelineViewActivity.this,
				FormDSARActivity.class);
		intent.putExtra("prospectID", _prospectID);
		intent.putExtra("visitNo", id);		
		
		if (isProspectClosed() || !lastItem)
			intent.putExtra("ro", true);
			
		startActivityForResult(intent, App.REQUEST_EDIT_DSAR);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_edit:
			edit();
			return true;
		case R.id.menu_delete:
			delete();
			return true;		
		case R.id.menu_data_pelengkap:
			prospect();
			return true;		
		case R.id.menu_add:
			addDSAR();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	private void delete() {
		new AlertDialog.Builder(new ContextThemeWrapper(this,
				R.style.Theme_Sherlock_Light_Dialog))
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.delete)
        .setMessage(R.string.delete_confirm)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	dialog.dismiss();
                _prospectDB.delete(_prospectID, Sessions.getUser(PipelineViewActivity.this).getNip());
                                
                TransactionLogDB trans = new TransactionLogDB(_db);
                UserInfo user = Sessions.getUser(PipelineViewActivity.this);
				trans.add(user.getNip(), "DELETE", "DELETE PROSPECT ID=" + String.valueOf(_prospectID));
                setResult(RESULT_OK);
                finish();
            }
        })        
        .setNegativeButton(R.string.no, null)
        .show(); 		
	}

	@Override
	protected void onDestroy() {
		unregisterReceiver(logoutReceiver);
		if (_db != null)
			_db.close();
		super.onDestroy();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == App.REQUEST_EDIT_PROSPECT) {
				//_isComplete = true;
				//_menuAdd.setVisible(_isComplete);
				_pipelineFragment.reload();
			}
													
			if (requestCode == App.REQUEST_EDIT_PIPELINE) {
				_pipelineFragment.reload();
				_dsarFragment.reload();
				setResult(Activity.RESULT_OK);
			}
			
			if (requestCode == App.REQUEST_EDIT_DSAR) {
				_pipelineFragment.reload();
				_dsarFragment.reload();
				
				setActionBar(_pager.getCurrentItem());
				//_menuAdd.setVisible(_pager.getCurrentItem() == 1 && !_dsarDB.hasOutstandingVisit(_prospectID));
			}
		}
	}
	
	class SimplePagerAdapter extends FragmentPagerAdapter {		
		
		private ArrayList<Fragment> fragments;
		private ArrayList<String> titles;
		
        public SimplePagerAdapter(FragmentManager fm, ArrayList<String> titles, ArrayList<Fragment> fragments) {
            super(fm);                       
            this.fragments = fragments;
            this.titles = titles;
        }

        @Override
        public Fragment getItem(int position) {                	
            return fragments.get(position);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titles.get(position);
        }

        @Override
        public int getCount() {
            return 2;
        }               
    }
	
	public void deleteDSAR(View v) {
	    final int id = (Integer)v.getTag(); 	 
	    new AlertDialog.Builder(new ContextThemeWrapper(this,
				R.style.Theme_Sherlock_Light_Dialog))	    
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setTitle(R.string.delete)
        .setMessage(R.string.delete_confirm)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            	dialog.dismiss();            	
                _dsarDB.delete(_prospectID, id, Sessions.getUser(PipelineViewActivity.this).getNip());
                TransactionLogDB trans = new TransactionLogDB(_db);
                
                UserInfo user = Sessions.getUser(PipelineViewActivity.this);
				trans.add(user.getNip(), "DELETE", "DELETE DSAR ID="+String.valueOf(id));
                _dsarFragment.reload();   
                
                setActionBar(_pager.getCurrentItem());
            }
        })        
        .setNegativeButton(R.string.no, null)
        .show(); 	
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onPageSelected(int pos) {
		if (_menuDSAR != null) {
		setActionBar(pos);
		}
	}
	
	private void setActionBar(int pos) {
		boolean open = pos == 0 && !_prospectDB.isClosed(_prospectID);
		_menuDSAR.setVisible(false);
		_menuAdd.setVisible(pos == 1 && !_prospectDB.isClosed(_prospectID) && !_dsarDB.hasOutstandingVisit(_prospectID));
		_menuEdit.setVisible(open);
		_menuDelete.setVisible(pos == 0);		
		_menuProspect.setVisible(open);
	}

	@Override
	public DatabaseHandler getDB() {		
		return _db;
	}
	
	public boolean isProspectClosed() {
		return _prospectDB.isClosed(_prospectID);
	}
}
